package com.totcy.atom.atom;

import android.text.TextUtils;

import org.datatist.sdk.autotrack.circle.CircleManager;
import org.datatist.sdk.autotrack.circle.net.HttpException;
import org.datatist.sdk.autotrack.circle.net.HttpManager;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AppVersionUpdate {

    @Test
    public void checkAppVersion() {

        String response = new OkhttpUtils().doGet("https://gitee.com/totcy/Atom/raw/master/resource/docs/AppCheckUpdate");
        System.out.println(response);
    }

    @Test
    public void downloadApp() {

        String downUrl = "https://github.com/gryllsi/resource/raw/master/apks/AtomApp.apk";


        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(downUrl)
                .addHeader("Accept-Encoding", "identity")
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            long lenth = response.body().contentLength();

            //将响应数据转化为输入流数据
            InputStream inputStream = response.body().byteStream();

            File file = new File("/Users/ios02/Documents/AndroidStudioProjects/Atom/resource/AtomAppTest.apk");
            OutputStream os = new FileOutputStream(file);

            long sum = 0;
            int bytesRead;
            byte[] buffer = new byte[2048];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);

                sum += bytesRead;
                int progress = (int) (sum * 1.0f / lenth * 100);
                // 下载中
                System.out.println("当前进度：" + progress + "%");
            }

            os.flush();
            os.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
